#!/bin/bash
set -xe

NEED_PROXY=false

if wget -q -O - https://ip.ddnsip.cn/ | grep -q "中国"; then
    echo "检测到中国IP,配置镜像源"
    sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
    go env -w GOPROXY=https://goproxy.cn,direct
    NEED_PROXY=true
fi

apk update && apk upgrade && apk add git

if $NEED_PROXY; then
    echo "配置 git 代理"
    git config --global url."https://ghfast.top/https://github.com".insteadOf "https://github.com"
fi

DIST_DIR="/workspace/dist"
mkdir -p $DIST_DIR

cd src/argon2g
go mod download
go build -ldflags='-s -w' -trimpath -o "$DIST_DIR/argon2g"

cd ..
git clone https://github.com/jsha/minica
cd minica
go mod download
go build -ldflags='-s -w' -trimpath -o "$DIST_DIR/minica"

cd ..
git clone https://github.com/tianon/gosu
cd gosu
go mod download
go build -ldflags='-s -w' -trimpath -o "$DIST_DIR/gosu"

cd ..
cd fileserv
go build -ldflags='-s -w' -trimpath -o "$DIST_DIR/fileserv" main.go

cd ..
cd ztnodeid
go build -ldflags='-s -w' -trimpath -o "$DIST_DIR/ztmkworld" cmd/mkworld/main.go

# cd ../..
# zip -r artifact-go.zip ./*
cd /workspace
mv dist helper && tar -czf helper.tar.gz helper/ && rm -rf helper